<?php

namespace plugin\coupon\app\admin\service;

use support\spark\exception\ApiException;
use support\spark\model\goods\Goods;
use plugin\coupon\app\admin\validate\CouponValidate;
use plugin\coupon\app\model\Coupon;
use plugin\coupon\app\model\CouponGoods;
use plugin\coupon\app\model\CouponReceiveLog;
use support\Db;

class CouponService
{
    public $couponType = [
        1 => '满减券',
        2 => '折扣券'
    ];

    public $couponStatus = [
        1 => '进行中',
        2 => '已作废',
        3 => '已过期',
        4 => '已领完'
    ];

    /**
     * 获取优惠券列表
     * @param $param
     * @return array
     */
    public function getList($param)
    {
        $limit = $param['limit'];
        $status = $param['status'];
        $name = $param['name'];

        $where = [];
        if (!empty($status)) {
            $where[] = ['status', '=', $status];
        }

        if (!empty($name)) {
            $where[] = ['name', 'like', '%' . $name . '%'];
        }

        $couponModel = new Coupon();
        $list = $couponModel->getPaginateList($where, ['*'], ['id' => 'desc'], [], $limit);
        foreach ($list['data'] as $k => $item) {
            $list['data'][$k]['type_txt'] = $this->couponType[$item['type']];
            $list['data'][$k]['status_txt'] = $this->couponStatus[$item['status']];
        }
        return dataReturn(0, 'success', $list);
    }

    /**
     * 添加优惠券
     * @param $param
     * @return array
     */
    public function addCoupon($param)
    {

        $validate = new CouponValidate();
        if (!$validate->check($param)) {
            throw  new ApiException($validate->getError());
        }
        if ($param['type'] == 1) {
            if (empty($param['amount'])) {
                throw  new ApiException('优惠券面额需要大于0');
            }
        } else {
            if (empty($param['discount'])) {
                throw  new ApiException('优惠折扣需要大于0');
            }
        }
        if ($param['is_limit_num'] == 1 && empty($param['total_num'])) {
            throw  new ApiException('发放数量要大于等于0');
        }
        if ($param['is_threshold'] == 1 && (!is_numeric($param['threshold_amount']) || $param['threshold_amount'] < 0)) {
            throw  new ApiException('门槛金额要大于等于0');
        }
        if ($param['validity_type'] == 1) {
            if (empty($param['datetime_range'])) {
                throw  new ApiException('有效期不能为空');
            } else {
                $param['start_time'] = $param['datetime_range'][0];
                $param['end_time'] = $param['datetime_range'][1];
            }
        } else {
            if (empty($param['receive_useful_day'])) {
                throw  new ApiException('领取有效期不能为空');
            }
        }
        unset($param['datetime_range']);

        if ($param['join_goods'] == 2 && empty($param['selectedGoods'])) {
            throw  new ApiException('活动商品不能为空');
        }

        Db::beginTransaction();
        try {
            $joinGoods = $param['selectedGoods'] ?? [];
            unset($param['selectedGoods']);
            $param['create_time'] = now();
            $couponModel = new Coupon();
            $couponId = $couponModel->insertGetId($param);
            if (!empty($joinGoods)) {
                $goodsBatch = [];
                foreach ($joinGoods as $vo) {
                    $goodsBatch[] = [
                        'coupon_id' => $couponId,
                        'goods_id' => $vo,
                        'create_time' => now()
                    ];
                }
                $couponGoodsModel = new CouponGoods();
                $couponGoodsModel->insertBatch($goodsBatch);
            }
            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            throw  new ApiException($e->getMessage());
        }

        return dataReturn(0, '新增成功');
    }

    /**
     * 获取优惠券关联的商品信息
     * @param $couponId
     * @return array
     */
    public function getCouponGoodsList($couponId)
    {
        $couponGoodsModel = new CouponGoods();
        $list = $couponGoodsModel->getAllList(['coupon_id' => $couponId], ['goods_id']);
        $goodsIds = [];
        foreach ($list as $vo) {
            $goodsIds[] = $vo['goods_id'];
        }
        $goodsModel = new Goods();
        return $goodsModel->getAllList([
            ['id', 'in', $goodsIds]
        ], ['name', 'price', 'stock']);
    }


}
